package pl.sind.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * Copyright 2009 Lukasz Wozniak
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
/**
 * Wrapper for downloaded message.<br/>
 * Should be handled immediately as underlying input stream from the server may
 * become unavailable due to timeouts connection close/reuse etc.
 * 
 * @author Lukasz Wozniak
 * 
 */
public class Download {
	private HttpResponse<?> response;
	private String fileName;
	private final Pattern p = Pattern.compile(".*filename\\=\"([\\w\\.]*)\".*");

	public Download(HttpResponse<?> response) {
		super();
		this.response = response;
		this.fileName = extractFilename(getContentType());
	}

	public InputStream getContent() throws HttpRequestException {
		return response.getInputStream();
	}

	public String getContentType() {
		return response.getHeader(HttpStrings.CONTENT_TYPE);
	}

	public String getFileName() {
		return fileName;
	}

	public void close() throws IOException {
		response.close();
	}
	
	/**
	 * Provide filename if it was supplied by the server.<br/>
	 * If not then its users problem to recognize content (he maybe knew what
	 * was downloaded) i name his files accordingly.
	 * 
	 * @param contentType
	 *            content type header from server
	 * @return filename or null if not found
	 */
	private String extractFilename(String contentType) {
		if (contentType != null) {
			Matcher m = p.matcher(contentType);
			if (m.matches()) {
				return m.group(1);
			}
		}
		return null;
	}

}
